#include "stdafx.h"
#include "DwmWindowHook.h"
#include "windows.h"
extern "C" 
{

typedef HRESULT (CALLBACK*_pfnDwmIsCompositionEnabled)
(
    __out BOOL* pfEnabled
    );
typedef BOOL
(CALLBACK* _pfnDwmDefWindowProc)(
    __in HWND hWnd,
    UINT msg,
    WPARAM wParam,
    LPARAM lParam,
    __out LRESULT *plResult
    );

static _pfnDwmIsCompositionEnabled pfnDwmIsCompositionEnabled = NULL;
static _pfnDwmDefWindowProc pfnDwmDefWindowProc = NULL;

static LONG OldProc = NULL;
LRESULT CustomProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam, bool* pfCallDWP)
{
    LRESULT lRet = 0;
    HRESULT hr = S_OK;
    bool fCallDWP = true; // Pass on to DefWindowProc?
	PAINTSTRUCT ps;

    fCallDWP = !pfnDwmDefWindowProc(hWnd, message, wParam, lParam, &lRet);

    // Handle window creation.

    *pfCallDWP = fCallDWP;

    return lRet;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    bool fCallDWP = true;
    BOOL fDwmEnabled = FALSE;
    LRESULT lRet = 0;

    // Winproc worker for custom frame issues.
    if (SUCCEEDED(pfnDwmIsCompositionEnabled(&fDwmEnabled))){
        lRet = CustomProc(hWnd, message, wParam, lParam, &fCallDWP);
    }
    if (fCallDWP)
    {
		if (OldProc)
			lRet = ((WNDPROC)OldProc)(hWnd, message, wParam, lParam);
		else
			lRet = DefWindowProc(hWnd, message, wParam, lParam);
    }
    return lRet;
}
void SetDwmWindowHook(int hwnd)
{
	HMODULE hm = LoadLibrary(L"dwmapi.dll");
	if (hm == NULL)
		return;
	pfnDwmIsCompositionEnabled = (_pfnDwmIsCompositionEnabled)GetProcAddress(hm,"DwmIsCompositionEnabled");
	pfnDwmDefWindowProc = (_pfnDwmDefWindowProc)GetProcAddress(hm,"DwmDefWindowProc");

	if (pfnDwmIsCompositionEnabled == NULL || pfnDwmDefWindowProc == NULL)
		return;
	
	OldProc = GetWindowLong((HWND)hwnd,GWL_WNDPROC);
	SetWindowLong((HWND)hwnd,GWL_WNDPROC,(LONG)WndProc);
}

}